import { Module } from 'vuex'
import PermissionStateTypes from './types'
import { AllStateTypes } from '../../types'
import router, { constantRoutes, asyncRoutes } from '@/router'
import { RouteRecordRaw } from 'vue-router'
import Layout from '@/layout'
/**
 *
 * @param v 传过来的每一级menu对象
 * @returns 返回menu数组
 */
const filterPermissionId = (v: any) => {
  const routes: any = {
    path: '',
  }
  const permissionIdList = JSON.parse(
    localStorage.getItem('userInfo')!,
  )?.permissionMenuIdText?.split(',')
  if (permissionIdList && permissionIdList.includes(v.id)) {
    routes.path = v.menuUrl
    if (v.redirect) routes.redirect = v.redirect
    routes.component =
      v.comUrl == 'Layout'
        ? Layout
        : () => import(/* @vite-ignore */ '@/views' + v.comUrl)
    routes.meta = {
      title: v.menuName,
      isShow: v.menuState ? true : false,
      isHome: v.menUrl == '/' ? true : false,
      // icon: v.menuPic && menuIcons.icons.filter((icon) => icon.name == v.menuPic)[0].val,
    }
    if (
      v.childMenuList &&
      Array.isArray(v.childMenuList) &&
      v.childMenuList.length > 0
    ) {
      routes.children = []
      // 递归处理子级menu
      v.childMenuList.forEach((vChild: any) =>
        routes.children.push(...hasPermission(vChild)),
      )
      if (routes.children.length == 0) delete routes.children
    }
  }
  return routes
}

/**
 *
 * @param adminAsyncRoutes 后端返回的menu的数组
 * @returns 过滤后的可访问的menu数组
 */
const hasPermission = (adminAsyncRoutes: any) => {
  const arr: RouteRecordRaw[] = []
  if (adminAsyncRoutes && Array.isArray(adminAsyncRoutes)) {
    adminAsyncRoutes.forEach((v: any) => {
      // 跟局premissionIdText 判断获取可访问menu数组
      const routes = filterPermissionId(v)
      routes.path && arr.push(routes)
    })
  } else {
    const routes = filterPermissionId(adminAsyncRoutes)
    routes.path && arr.push(routes)
  }
  return arr
}

const permissionModule: Module<PermissionStateTypes, AllStateTypes> = {
  namespaced: true,
  state: {
    roles: [], // 用户权限集合
    routes: constantRoutes, // 可访问的路由集合
    selectedMenuList: [],
    asyncRoute: [],
    selectMenuLeft: [],
  },
  mutations: {
    setRoles(state: PermissionStateTypes, roles) {
      state.roles = roles
    },
    setRoutes(state: PermissionStateTypes, routes) {
      // 静态路由 + 异步中有权限的路由
      state.routes = constantRoutes.concat(routes)
    },
    setSelectMenuLeft(state: PermissionStateTypes, menuInfo) {
      state.selectMenuLeft = menuInfo
    },
    addSelectedMenuList(state: PermissionStateTypes, menuInfo) {
      if (menuInfo.path == '/') return
      const index = state.selectedMenuList.findIndex(
        (item) => item.path === menuInfo.path,
      )
      if (index === -1) {
        state.selectedMenuList.push(menuInfo)
      }
    },
    removeSelectedMenuList(state: PermissionStateTypes, menuInfo) {
      const index = state.selectedMenuList.findIndex(
        (item) => item.path === menuInfo.path,
      )
      if (index !== -1) {
        state.selectedMenuList.splice(index, 1)
      }
    },
    clesrSelectedMenuList(state: PermissionStateTypes) {
      state.selectedMenuList = []
    },
    setAsyncRoute(state, data) {
      state.asyncRoute = data
    },
  },
  actions: {
    getPermissionRoutes(store) {
      // TODO: api request 当前暂时跳过请求(根据业务逻辑请求后端获取路由信息)
      // const newRoutes: Array<RouteRecordRaw> = [...constantRoutes]
      // const accessedRoutes: RouteRecordRaw[] = []
      const accessedRoutes: RouteRecordRaw[] = asyncRoutes
      // const adminAsyncRoutes =
      //   store.state.asyncRoute?.length > 0
      //     ? store.state.asyncRoute
      //     : localStorage.getItem('adminAsyncRoutes') &&
      //       JSON.parse(localStorage.getItem('adminAsyncRoutes')!)
      // if (adminAsyncRoutes && Array.isArray(adminAsyncRoutes)) {
      //   // 过滤得到menu数组
      //   const routes = hasPermission(adminAsyncRoutes)
      //   accessedRoutes.push(...routes)
      // }
      // TODO: 将新的路由正确放入路有选项的children中
      for (const r of accessedRoutes) {
        if (r.meta?.parent) {
          router.addRoute(r.meta.parent as string, r)
        } else {
          router.addRoute(r)
        }
      }
      router.options.routes = constantRoutes.concat(accessedRoutes)

      console.log(router.options.routes)
      // 触发视图变化
      store.commit('setRoutes', accessedRoutes)
    },
  },
  getters: {
    routes(state) {
      return state.routes
    },
    selectedMenuList(state) {
      return state.selectedMenuList
    },
    selectMenuLeft(state) {
      return state.selectMenuLeft
    },
    asyncRoute(state) {
      return state.asyncRoute
    },
  },
}

export default permissionModule
